package com.springlearn.zhoufei.other.spring.demo6;

/**
 * 描述该类- JPA
 *
 * @author zhoufei
 * @class: StudentJDBCTemplate
 * @date 2020/10/3  9:54
 * @Verson 1.0 -2020/10/3  9:54
 * @see
 */

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

public class StudentJDBCTemplate implements StudentDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;
    private PlatformTransactionManager transactionManager;
    
    // 设置数据源
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }
    
    public PlatformTransactionManager getTransactionManager() {
        return transactionManager;
    }
    
    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }
    
    @Override
    public void insert() {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            
            Integer age = 12;
            String name = "xiao4";
            String SQL = "insert into Student (name, age) values (?, ?)";
            jdbcTemplateObject.update(SQL, name, age);
            
            String SQL2 = "update Student set age = ? where id = ?";
            jdbcTemplateObject.update(SQL2, 21, 25);
            transactionManager.commit(status);
            
        } catch (DataAccessException e) {
            System.out.println("异常,事务回滚");
            transactionManager.rollback(status);
            throw e;
        }
        
    }
}